package cn.xyz.mianshi.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import cn.xyz.commons.constants.DBConstants;
import cn.xyz.commons.constants.MsgType;
import cn.xyz.mianshi.model.BaseExample;
import cn.xyz.service.KXMPPServiceImpl;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;

import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.model.MapReduceAction;
//import com.shiku.imserver.message.hander.SendMessageHandler;
import com.shiku.mongodb.morphia.MongoConfig;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.support.mongo.MongoOperator;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.Room.Member;
import cn.xyz.repository.mongo.MongoRepository;

/**
 * Tigase 相关的管理类
 * @author root
 *
 */
@Slf4j
@Service(TigaseManagerImpl.BEAN_ID)
public class TigaseManagerImpl extends MongoRepository<Object, ObjectId> implements InitializingBean{
	
	public static final String BEAN_ID = "TigaseManagerImpl";

	@Autowired(required=false)
	private MongoClient tigMongoClient;


	private MongoDatabase chatMsgDB;

	public MongoDatabase getChatMsgDB() {
		return chatMsgDB;
	}


	@Override
	public Datastore getDatastore() {
		return SKBeanUtils.getDatastore();
	}

	@Override
	public Class<Object> getEntityClass() {
		return null;
	}

	private MongoDatabase lastMsgDB;

	public MongoDatabase getLastMsgDB() {
		return lastMsgDB;
	}

	private MongoDatabase imRoomDB;

	public MongoDatabase getImRoomDB() {
		return imRoomDB;
	}



	protected static final int DB_REMAINDER=10000;

	@Autowired(required=false)
	private MongoConfig mongoConfig;




	@Override
	public void afterPropertiesSet() throws Exception {
		if(null!=tigMongoClient) {
			chatMsgDB = tigMongoClient.getDatabase(DBConstants.CHAT_MSGS_DB);
			lastMsgDB = tigMongoClient.getDatabase(DBConstants.LASTCHAT_DB);
			String roomDbName = mongoConfig.getRoomDbName();
			imRoomDB = tigMongoClient.getDatabase(roomDbName);
		}

	}


	public MongoCollection<Document> getMongoCollection(MongoDatabase database,int userId) {
		int remainder=0;
		if(userId>KConstants.MIN_USERID) {
			remainder=userId/DB_REMAINDER;
		}
		return database.getCollection(String.valueOf(remainder));
	}

	public MongoCollection<Document> getMongoCollection(MongoDatabase database,String tableName) {


		return database.getCollection(tableName);
	}


	public DBCollection getCollection(String databaseName,int userId) {
		int remainder=0;
		if(userId>KConstants.MIN_USERID) {
			remainder=userId/DB_REMAINDER;
		}
		return SKBeanUtils.getLocalSpringBeanManager().getTigMongoClient().getDB(databaseName).getCollection(String.valueOf(remainder));
	}
	public List<String> getCollectionList(String databaseName) {
		List<String> list=new ArrayList<>();

		 Set<String> collectionNames = SKBeanUtils.getLocalSpringBeanManager().getTigMongoClient().getDB(databaseName).getCollectionNames();
		for (String s : collectionNames) {
			 list.add(s);
	      }
		 list.remove("system.indexes");
		 return list;
	}
	public List<String> getCollectionList(MongoDatabase database) {
		List<String> list=new ArrayList<>();

		 MongoIterable<String> collectionNames = database.listCollectionNames();
		for (String s : collectionNames) {
			 list.add(s);
	      }
		 list.remove("system.indexes");
		 return list;
	}


	  public  void updateMsgIsReadStatus(int sender,String msgId){
	    	if(null==msgId)
				return;
			Document query = new Document("messageId",msgId);
			getMongoCollection(getChatMsgDB(), sender).updateMany(query, new Document("$set",new BasicDBObject("isRead", 1)));
			
	  }
	
	public void deleteLastMsg(int userId,String jid){
		Document query=new Document("jid", jid);
		if(0!=userId)
			query.append("userId", userId);
		getMongoCollection(lastMsgDB, userId).deleteMany(query);
	}

	public List<Document> queryChatMsgsList(String sender,String receiver,long startTime,
			 long endTime,  int pageIndex,int pageSize){

		Document qUserClearMsg = new Document();
		qUserClearMsg.put("sender", sender);
		qUserClearMsg.put("receiver", receiver);
		Document first = getMongoCollection(getChatMsgDB(), "shiku_msgs").find(qUserClearMsg).first();
		if(first != null)
		{
			if (startTime > 0 && startTime < first.getLong("timeSend"))
			{
				startTime =first.getLong("timeSend");

			}
		}
		Document q = new Document();
		q.put("sender", sender);
		q.put("receiver", receiver);
		/*if(maxType>0)
			q.put("contentType",new BasicDBObject(MongoOperator.LT, maxType));*/
		if (0 != startTime&&0 != endTime){
			q.put("timeSend", new Document("$gte", startTime).append("$lte", endTime));
		}else if (0 != startTime||0!= endTime){
			if(0!=startTime)
				q.put("timeSend", new Document("$gte", startTime));
			else{
				q.put("timeSend", new Document("$lte", endTime));
			}
		}

		List<Document> result = Lists.newArrayList();
		int userId=new Integer(parseBareUserId(sender));
		MongoCursor<Document> cursor = getMongoCollection(getChatMsgDB(), userId).find(q).sort(new Document("ts", -1)).skip(pageIndex * pageSize)
				.limit(pageSize).iterator();
		try {
			while (cursor.hasNext()) {
				result.add(cursor.next());
			}
		} finally {
			if(null!=cursor)
				cursor.close();
		}
		return result;
	}
	
	public List<Document> queryMucMsgsList( String roomId, long startTime,
			 long endTime,  int pageIndex, int pageSize){
		Document q = new Document();

		List<Document> result= Lists.newArrayList();
		log.info("[queryMucMsgsList]=startTime="+startTime+",endTime="+endTime+",roomId="+roomId);
		//q.put("room_jid", roomId);
		/*if(maxType>0)
			q.put("contentType",new BasicDBObject(MongoOperator.LT, maxType));*/
		ObjectId roomObjId = SKBeanUtils.getRoomManager().getRoomId(roomId);
		if (null != roomObjId) {
			Member member = SKBeanUtils.getRoomManager().getMember(roomObjId, ReqUtil.getUserId());
			if(null!=member){
				log.info("[queryMucMsgsList]111100=startTime="+startTime+",endTime="+endTime+",roomId="+roomId+",getCreateTime="+member.getCreateTime());
				if (startTime > 0 && null != member && startTime < member.getCreateTime()*1000)
				{
					startTime = member.getCreateTime()*1000;
					log.info("[queryMucMsgsList]11110011=startTime="+startTime+",endTime="+endTime+",roomId="+roomId+",startTime="+startTime);
				}
			}
			else{
				return result;
			}
		}
		log.info("[queryMucMsgsList]111100=startTime="+startTime+",endTime="+endTime+",roomId="+roomId+",startTime="+startTime);
		if (0 != startTime&&0 != endTime){
			q.put("timeSend", new Document("$gte", startTime).append("$lte", endTime));
		}else if (0 != startTime||0!= endTime){
			if(0!=startTime)
				q.put("timeSend", new Document("$gte", startTime));
			else
				q.put("timeSend", new Document("$lte", endTime));
		}
		log.info("[queryMucMsgsList]1111=startTime="+startTime+",endTime="+endTime+",roomId="+roomId);
		// 群聊漫游不返回领取红包消息 contentType = 83
		q.put("contentType", new BasicDBObject(MongoOperator.NE, KXMPPServiceImpl.OPENREDPAKET));


		log.info("[queryMucMsgsList]0000=startTime="+startTime+",endTime="+endTime+",roomId="+roomId);
	/*	DBObject projection=new BasicDBList();
		projection.put("body", 1);*/
		MongoCursor<Document> cursor = getImRoomDB().getCollection(DBConstants.RoomMsg_Collection_Prefix+roomId).find(q).sort(new BasicDBObject("ts", -1)).skip(pageIndex * pageSize)
				.limit(pageSize).iterator();
		log.info("[queryMucMsgsList]=startTime="+startTime+",endTime="+endTime+",roomId="+roomId);
		try {
			while (cursor.hasNext()) {
				result.add(cursor.next());
			}
		} finally {
			if(null!=cursor)
				cursor.close();
		}
		return result;
	}
	
	
	public List<Document> queryLastChatList(long startTime, long endTime,int pageSize){
		 Integer userId = ReqUtil.getUserId();
		 List<Document> resultList = Lists.newArrayList();
		BasicDBObject query=new BasicDBObject();
		if (0 != startTime&&0 != endTime)
			query.put("timeSend", new BasicDBObject("$gt", startTime).append("$lt", endTime));
		if (0 != startTime||0!= endTime){
			if(0!=startTime)
				query.put("timeSend", new BasicDBObject("$gt", startTime));
			else
				query.put("timeSend", new BasicDBObject("$lt", endTime));
		}
		MongoCursor<Document> cursor =null;
		Document dbObj=null;
		Document sort = new Document("timeSend", -1);
		List<String> roomJidList = SKBeanUtils.getRoomManager().queryUserRoomsJidList(userId);
		if(null!=roomJidList&&0<roomJidList.size()){
			query.append("jid", new BasicDBObject(MongoOperator.IN, roomJidList));
			
			cursor=lastMsgDB.getCollection(DBConstants.LASTCHAT_MUC_COLLECTION).find(query).sort(sort).limit(pageSize).iterator();
			try {
				while (cursor.hasNext()) {
					 dbObj = cursor.next();
					 resultList.add(dbObj);
				}
			} finally {
				if(null!=cursor)
					cursor.close();
			}


			query.remove("jid");
		}
		query.append("userId", userId.toString());
		cursor=getMongoCollection(lastMsgDB, userId).find(query)
				.sort(sort).limit(pageSize)
				.iterator();
		try {
			while (cursor.hasNext()) {
				dbObj = cursor.next();
				 if((int)dbObj.get("isRoom")!=1){
					 try {
						 String nickName = SKBeanUtils.getUserManager().getNickName(Integer.valueOf((String)dbObj.get("jid")));
						 dbObj.put("toUserName",nickName);
					 }
					catch(Exception ex) {
						
					}
					
				 }
				resultList.add(dbObj);
			}
		} finally {
			if(null!=cursor)
				cursor.close();
		}
		log.info("[ww]:queryLastChatList=end");
		return resultList;
	}

	public static String parseBareUserId(String jid) {
		int slashIndex = jid.indexOf('/');
		if (slashIndex < 0) {
			return jid;
		} else if (slashIndex == 0) {
			return "";
		} else {
			return jid.substring(0, slashIndex);
		}
	}

	/**
	 * 获取单聊消息数量
	 * @return
	 */
	public long getMsgCountNum() {
		long count=0;
		MongoIterable<String> listCollectionNames = getChatMsgDB().listCollectionNames();
		for (String string : listCollectionNames) {
			count+=getChatMsgDB().getCollection(string).count();
		}
		return count;
	}
	
	
	
	
	/**
	 * 单聊消息数量统计      时间单位  每日、每月、每分钟、每小时
	 * @param startDate
	 * @param endDate
	 * @param counType  统计类型   1: 每个月的数据      2:每天的数据       3.每小时数据   4.每分钟的数据 (小时)   
	 */
	public List<Object> getChatMsgCount(String startDate, String endDate, short counType){
		
		List<Object> countData = new ArrayList<>();
		
		long startTime = 0; //开始时间（秒）
		long endTime = 0; //结束时间（秒）,默认为当前时间
		
		/**
		 * 如时间单位为月和天，默认开始时间为当前时间的一年前 ; 时间单位为小时，默认开始时间为当前时间的一个月前;
		 * 时间单位为分钟，则默认开始时间为当前这一天的0点
		 */
		long defStartTime = counType==4? DateUtil.getTodayMorning().getTime()
				: counType==3 ? DateUtil.getLastMonth().getTime(): DateUtil.getLastYear().getTime();
		
		startTime = StringUtil.isEmpty(startDate) ? defStartTime :DateUtil.toDate(startDate).getTime();
		endTime = StringUtil.isEmpty(endDate) ? System.currentTimeMillis() : DateUtil.toDate(endDate).getTime();
				
		BasicDBObject queryTime = new BasicDBObject("$ne",null);
		
		if(startTime!=0 && endTime!=0){
			queryTime.append("$gt", startTime);
			queryTime.append("$lt", endTime);
		}
		
		BasicDBObject query = new BasicDBObject("ts",queryTime);


		
		String mapStr = "function Map() { "
	            + "var date = new Date(this.ts);"
	            +  "var year = date.getFullYear();"
				+  "var month = (\"0\" + (date.getMonth()+1)).slice(-2);"  //month 从0开始，此处要加1
				+  "var day = (\"0\" + date.getDate()).slice(-2);"
				+  "var hour = (\"0\" + date.getHours()).slice(-2);"
				+  "var minute = (\"0\" + date.getMinutes()).slice(-2);"
				+  "var dateStr = date.getFullYear()"+"+'-'+"+"(parseInt(date.getMonth())+1)"+"+'-'+"+"date.getDate();";

				if(counType==1){ // counType=1: 每个月的数据
					mapStr += "var key= year + '-'+ month;";
				}else if(counType==2){ // counType=2:每天的数据
					mapStr += "var key= year + '-'+ month + '-' + day;";
				}else if(counType==3){ //counType=3 :每小时数据
					mapStr += "var key= year + '-'+ month + '-' + day + '  ' + hour +' : 00';";
				}else if(counType==4){ //counType=4 :每分钟的数据
					mapStr += "var key= year + '-'+ month + '-' + day + '  ' + hour + ':'+ minute;";
				}

				mapStr += "emit(key,1);}";

		 String reduce = "function Reduce(key, values) {" +
			                "return Array.sum(values);" +
	                    "}";

		 Map<String,Double> map = new HashMap<String,Double>();
		//获得单聊消息集合对象
			MongoIterable<String> collectionNames = getChatMsgDB().listCollectionNames();
			for (String str : collectionNames) {
				MongoCollection collection = getChatMsgDB().getCollection(str,DBObject.class);
				if(0==collection.count(query))
					continue;
				MongoCursor iterator = collection.mapReduce(mapStr, reduce, DBObject.class).iterator();
				 Double value=null;
				 String id=null;
				while (iterator.hasNext()) {
					DBObject obj = (DBObject) iterator.next();
					id=(String)obj.get("_id");
					 value= (Double)obj.get("value");
					if(null!=map.get(id)) {
						map.put(id,map.get(id)+value);
					}else {
						map.put(id,value);
					}

					//System.out.println("====>>>>单聊消息"+JSON.toJSON(obj));
				}
			}
		countData=map.entrySet().stream().collect(Collectors.toList());
		map.clear();

		return countData;
	}
	
	
	
	
	/**
	 * 群聊消息数量统计      时间单位  每日、每月、每分钟、每小时
	 * @param startDate
	 * @param endDate
	 * @param counType  统计类型   1: 每个月的数据      2:每天的数据       3.每小时数据   4.每分钟的数据 (小时)   
	 */
	public List<Object> getGroupMsgCount(String roomId,String startDate, String endDate, short counType){
		
		//获得群聊消息集合对象
		DBCollection collection = SKBeanUtils.getImRoomDatastore().getDB().getCollection("mucmsg_"+roomId);
		
		if(collection==null || collection.count()==0){
			System.out.println("暂无数据");
			throw new ServiceException("暂无数据");
		}
		
		List<Object> countData = new ArrayList<Object>();
		
		long startTime = 0; //开始时间（秒）
		
		long endTime = 0; //结束时间（秒）,默认为当前时间
		
		/**
		 * 如时间单位为月和天，默认开始时间为当前时间的一年前 ; 时间单位为小时，默认开始时间为当前时间的一个月前;
		 * 时间单位为分钟，则默认开始时间为当前这一天的0点
		 */
		long defStartTime = counType==4? DateUtil.getTodayMorning().getTime()
				: counType==3 ? DateUtil.getLastMonth().getTime(): DateUtil.getLastYear().getTime();
		
		startTime = StringUtil.isEmpty(startDate) ? defStartTime :DateUtil.toDate(startDate).getTime();
		endTime = StringUtil.isEmpty(endDate) ? System.currentTimeMillis() : DateUtil.toDate(endDate).getTime();
				
		BasicDBObject queryTime = new BasicDBObject("$ne",null);
		
		if(startTime!=0 && endTime!=0){
			queryTime.append("$gt", startTime);
			queryTime.append("$lt", endTime);
		}
		
		BasicDBObject query = new BasicDBObject("ts",queryTime);
		
		
		
		String mapStr = "function Map() { "   
	            + "var date = new Date(this.ts);"
	            +  "var year = date.getFullYear();"
				+  "var month = (\"0\" + (date.getMonth()+1)).slice(-2);"  //month 从0开始，此处要加1
				+  "var day = (\"0\" + date.getDate()).slice(-2);"
				+  "var hour = (\"0\" + date.getHours()).slice(-2);"
				+  "var minute = (\"0\" + date.getMinutes()).slice(-2);"
				+  "var dateStr = date.getFullYear()"+"+'-'+"+"(parseInt(date.getMonth())+1)"+"+'-'+"+"date.getDate();";
				
				if(counType==1){ // counType=1: 每个月的数据
					mapStr += "var key= year + '-'+ month;";
				}else if(counType==2){ // counType=2:每天的数据
					mapStr += "var key= year + '-'+ month + '-' + day;";
				}else if(counType==3){ //counType=3 :每小时数据
					mapStr += "var key= year + '-'+ month + '-' + day + '  ' + hour +' : 00';";
				}else if(counType==4){ //counType=4 :每分钟的数据
					mapStr += "var key= year + '-'+ month + '-' + day + '  ' + hour + ':'+ minute;";
				}
	           
				mapStr += "emit(key,1);}";
		
		 String reduce = "function Reduce(key, values) {" +
			                "return Array.sum(values);" +
	                    "}";
		 MapReduceCommand.OutputType type =  MapReduceCommand.OutputType.INLINE;//
		 MapReduceCommand command = new MapReduceCommand(collection, mapStr, reduce,null, type,query);

		 MapReduceOutput mapReduceOutput = collection.mapReduce(command);
		 Iterable<DBObject> results = mapReduceOutput.results();
		 Map<String,Double> map = new HashMap<String,Double>();
		for (Iterator iterator = results.iterator(); iterator.hasNext();) {
			DBObject obj = (DBObject) iterator.next();
			 
			map.put((String)obj.get("_id"),(Double)obj.get("value"));
			countData.add(JSON.toJSON(map));
			map.clear();
			//System.out.println("======>>>群消息统计 "+JSON.toJSON(obj));
			
		}
		
		return countData;
	}

	
	public PageResult chatLogsAll( long startTime,long endTime, int sender,
			int receiver,int page,
			 int limit, String keyWord) throws Exception {
		MongoCollection<Document> dbCollection  = getChatMsgDB().getCollection("1000");
		Document q = new Document();

		UserManagerImpl userManager = SKBeanUtils.getUserManager();
		q.put("direction", 0);
		if (0 != receiver) {
			q.put("receiver", receiver+"");
		}
		if (0 != sender) {
			q.put("sender",sender+"");
		}
		if(!StringUtil.isEmpty(keyWord)){
			q.put("content", new Document(MongoOperator.REGEX,keyWord));
		}

		if (0 != startTime)
			q.put("ts", new Document("$gte", startTime));
		if (0 != endTime)
			q.put("ts", new Document("$lte", endTime));

		long total = dbCollection.count(q);

		java.util.List<Document> pageData = Lists.newArrayList();

		MongoCursor<Document> iterator = dbCollection.find(q).sort(new Document("_id", -1)).skip((page - 1) * limit).limit(limit).iterator();
		PageResult<Document> result = new PageResult<Document>();
		try {
			while (iterator.hasNext()) {
				Document dbObj = iterator.next();
				JSONObject body = JSONObject.parseObject(dbObj.getString("message"));
				if(null==body)
					continue;
				if (null != dbObj.get("isEncrypt") && true==dbObj.getBoolean("isEncrypt")) {
					dbObj.put("isEncrypt", 1);
				} else {
					dbObj.put("isEncrypt", 0);
				}
				try {
					dbObj.put("sender_nickname", userManager.getNickName(Integer.valueOf(dbObj.getString("sender"))));
				} catch (Exception e) {
					dbObj.put("sender_nickname", "未知");
				}
				try {
					dbObj.put("receiver_nickname",userManager.getNickName(Integer.valueOf(dbObj.getString("receiver"))));
				} catch (Exception e) {
					dbObj.put("receiver_nickname", "未知");
				}
				try {
					if(ReqUtil.getUserId() == KConstants.systemAccount.ADMIN_CONSOLE_ACCOUNT2)
					{
						dbObj.put("content",dbObj.get("content"));
					}
					else{
						dbObj.put("content", "----");
					}
				} catch (Exception e) {
					dbObj.put("content", "--");
				}

				pageData.add(dbObj);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			iterator.close();
		}

		result.setData(pageData);
		result.setCount(total);
		return result;
	}
	public void chatLogsAllDel( long startTime,long endTime, int sender,
			 int receiver, int pageIndex,
			 int pageSize) {
		List<String> collectionList = getCollectionList(getChatMsgDB());
		Document q = new Document();
		if (0 != sender) {
			q.put("sender", new BasicDBObject("$eq", sender));
		}
		if (0 != receiver) {
			q.put("receiver", new BasicDBObject("$eq", receiver));
		}
		if (0 != startTime)
			q.put("ts", new BasicDBObject("$gte", startTime));
		if (0 != endTime)
			q.put("ts", new BasicDBObject("$lte", endTime));
		for (String string : collectionList) {
			getChatMsgDB().getCollection(string).deleteMany(q);
		}
	}

	public void deleteChatMsgs( String msgId, int type) {

		MongoCollection<Document> collection = chatMsgDB.getCollection("1000");
		Document query = new Document();
		collection.createIndex(new Document("timeSend", -1));

		if (0 == type) {
			if (StringUtil.isEmpty(msgId))
				throw new ServiceException("参数msgId错误");

			else {

				List<ObjectId> msgIdList = new ArrayList<ObjectId>();
				String[] msgIds = StringUtil.getStringList(msgId);
				for (String strMsgId : StringUtil.getStringList(msgId)) {
					msgIdList.add(new ObjectId(strMsgId));
				}
				query.append("_id", new Document(MongoOperator.IN,msgIdList));

				//把文件 url 加到要删除的文件记录表中,用以删除文件
				joinFileUriToDelFielsCollection(collection,query);
				collection.deleteMany(query);

			}
		} else if (1 == type) { // 删除一个月前的聊天记录
			long onedayNextDay = DateUtil.getOnedayNextDay(DateUtil.currentTimeSeconds(), 30, 1);
			System.out.println("上个月的时间：" + onedayNextDay);
			query.put("timeSend", new BasicDBObject("$lte", onedayNextDay));
			//把文件 url 加到要删除的文件记录表中,用以删除文件
			joinFileUriToDelFielsCollection(collection,query);

			collection.deleteMany(query);

		} else if (2 == type) {
			final int num = 100000;

			long count = collection.count();
			if (count <= num)
				throw new ServiceException( "消息总数量数量少于" + num +"条" );
			//删除十万条前的聊天记录
			Document first = collection.find().sort(new Document("timeSend", -1)).skip(num).first();

			if(null==first)
				return;

			query.append("timeSend",new Document(MongoOperator.LT, first.getLong("timeSend")));

			//把文件 url 加到要删除的文件记录表中,用以删除文件
			joinFileUriToDelFielsCollection(collection,query);

			collection.deleteMany(query);
		}

	}


	//把文件 url 加到要删除的文件记录表中
	public  void joinFileUriToDelFielsCollection(MongoCollection<Document> collection , Document query){

		MapReduceIterable<Document> documents = collection.mapReduce("function Map() { emit(this.messageId,this.content);}",
				"function Reduce(key, values) {  return -1 != (''+values).indexOf('http') ? values.toString() : ''; }");
		documents.collectionName("del_files").databaseName("resources").action(MapReduceAction.MERGE);
		Document newQuery = query.append("contentType",new Document(MongoOperator.IN,MsgType.FileTypeArr)); // 2:图片 3:语音 6:视频 9:文件
		documents.filter(newQuery);
		documents.toCollection();
		//documents.iterator().close();
		query.remove("contentType");
	}

	/**
	 * 个人删除群消息
	 * @param roomID
	 * @param UserID
	 */
	public  void deleteRoomMsg(String roomID,int UserID)
	{
		ObjectId roomObjId=null;
		try {
			roomObjId=new ObjectId(roomID);
		}catch (Exception e){

		}
		Document document = new Document();
		document.append("createTime", DateUtil.currentTimeSeconds());
		SKBeanUtils.getRoomManager().updateRoomMemberToDB(roomObjId,UserID,document);
	}


	
	
	
	
}
